package com.crm.crm.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crm.crm.annotation.Log;
import com.crm.crm.domain.BusinessOpportunity;
import com.crm.crm.domain.BusinessPool;
import com.crm.crm.domain.BusinessRecord;
import com.crm.crm.domain.dto.business.*;
import com.crm.crm.domain.vo.ClueVo;
import com.crm.crm.domain.vo.PageResult;
import com.crm.crm.domain.vo.business.BusinessRecordVo;
import com.crm.crm.domain.vo.business.result.Result;
import com.crm.crm.domain.vo.business.BusinessVo;
import com.crm.crm.service.BusinessService;
import com.crm.crm.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("/business")
public class BusinessController {
    @Autowired
    private BusinessService businessService;
    @Autowired
    private UserService userService;
    //新增商机
    @Log("新增商机")
    @PostMapping
    public Result add(@RequestBody NewBusinessDto newBusinessDto) {
        String add = businessService.add(newBusinessDto);
        if (add != null) {
            return Result.error(add);
        }
        return Result.success();
    }


    //    分页查询
    @GetMapping("/list")
    public Result list(BusinessListDto dto,
                       @RequestParam Map<String, String> params) {
        dto.setBeginCreateTime(params.get("params[beginCreateTime]"));
        dto.setEndCreateTime(params.get("params[endCreateTime]"));
        // 创建分页对象（pageNum 是当前页码，pageSize 是每页记录数）
        Page<BusinessOpportunity> page = new Page<>(dto.getPageNum(), dto.getPageSize());

        // 调用 service 分页查询方法
        Page<BusinessOpportunity> resultPage = businessService.list(dto, page);
        // 将 Page<BusinessOpportunity> 转换为 List<BusinessVo>
        List<BusinessVo> voList = resultPage.getRecords().stream()
                .map(business -> {
                    BusinessVo vo = new BusinessVo();
                    BeanUtils.copyProperties(business, vo);
                    return vo;
                })
                .toList();

// 构造最终结果：将 total 和 rows 提升到顶层
        Result result = Result.success();
        result.put("total", resultPage.getTotal());
        result.put("rows", voList);
        return result;

    }

    //修改归属信息
    @Log("分配,变更归属人")
    @PutMapping("/assignment")
    public Result update(@RequestBody BusinessBatchDTO dto) {
        log.info("修改归属信息参数：{}", dto);
        Integer count = businessService.updateById(dto);
        log.info("修改归属信息结果：{}", count);
        if (count == 3) {
            return Result.error("保存量达到上限，最多选择两条商机");
        } else if (count == 4) {
            return Result.error("修改后用户持有总数会大于最大可持有数");
        } else if (count <= 2 && count > 0) {
            return Result.success("操作成功");
        }
        return Result.error("操作失败");
    }


    /**
     * 根据id查询客户资料详情
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result getBusinessDetailsById(@PathVariable("id") Long id) {
        BusinessVo businessDetailsList = businessService.getBusinessDetailsById(id);
        return Result.success(businessDetailsList);
    }

    ///**
    // * 历史沟通记录列表查询
    // *
    // * @param businessId
    // * @return
    // */
    //@GetMapping("/record/list")
    //public Result getBusinessRecordListById(Integer businessId) {
    //    log.info("历史沟通记录列表查询参数：{}", businessId);
    //    return Result.success(businessService.getBusinessRecordListById(businessId));
    //}

    /**
     * 修改商机信息并保存沟通记录
     *
     * @param businessMessageDto
     * @return
     */
    @Log("修改商机信息")
    @PostMapping("/record")
    public Result addAndUpdateBusiness(@RequestBody BusinessMessageDto businessMessageDto) {
        businessService.addAndUpdateBusiness(businessMessageDto);
        return Result.success();
    }

    @GetMapping("/record/list")
    public Result getRecordList(@RequestParam("businessId") Long id ){

        List<BusinessRecordVo> businessRecordList = businessService.getRecordList(Math.toIntExact(id));
        return Result.success(businessRecordList);
    }

    /**
     * 踢回公海
     *
     * @param id
     * @param reason_reporting
     * @return
     */
    @Log("踢回公海")
    @PutMapping("/back/{id}/{reason_reporting}")
    public Result back(@PathVariable("id") Long id, @PathVariable("reason_reporting") String reason_reporting) {
        boolean back = businessService.back(id, reason_reporting);
        if (!back) {
            return Result.error("回退失败");
        } else {
            return Result.success();
        }
    }

    /**
     * 公海列表查询
     *
     * @param businessPoolDto
     * @return
     */
    @GetMapping("/pool")
    public Result pool(BusinessPoolDto businessPoolDto) {
        PageResult<BusinessPool> pageResult = businessService.getPage(businessPoolDto);
        return Result.success().put("total", pageResult.getTotal())
                .put("rows", pageResult.getRows());
    }

    /**
     * 移出公海
     *
     * @param dto
     * @return
     */
    @Log("移出公海")
    @PutMapping("/gain")
    public Result gain(@RequestBody BusinessBatchDTO dto) {
        String gain = businessService.gain(dto);
        if (gain != null) {
            return Result.error(gain);
        }
        return Result.success();
    }
}
